<template>
    <div id="Login">
        <div class="loginForm">
            <el-form :model="loginForm" :rules="loginRules" ref="loginForm">
                <h3 class="title">东软电商后台系统</h3>
                <el-form-item prop="username">
                    <el-input v-model="loginForm.username" prefix-icon="el-icon-user-solid" placeholder="账号"></el-input>
                </el-form-item>
                <el-form-item prop="password">
                    <el-input v-model="loginForm.password" prefix-icon="el-icon-s-goods" type="password" placeholder="密码" show-password></el-input>
                </el-form-item>
                <el-form-item prop="code">
                    <el-input v-model="loginForm.code" prefix-icon="el-icon-circle-check" placeholder="验证码" style="width: 63%"></el-input>
                    <div class="login-code" @click="refreshCode">
                        <s-identify :identifyCode="identifyCode"></s-identify>
                    </div>
                </el-form-item>
                <el-checkbox v-model="rememberMe" style="margin:0px 0px 25px 0px;">记住密码</el-checkbox>
                <el-form-item>
                    <el-button :loading="loading" type="primary" style="width: 100%;"
                     @click.native.prevent="handleLogin">
                        <span v-if="!loading">登 录</span>
                        <span v-else>登 录 中...</span>
                    </el-button>
                </el-form-item>
            </el-form>
        </div>
        <div class="login_footer">
          <span>@ {{Year}} E-commerce management system</span>
          <span> 东软实训：奇思妙想小组</span>
        </div>
    </div>
</template>

<script>
import SIdentify from '../../components/SIdentify'

const Base64 = require('js-base64').Base64
export default {
  components: {
    SIdentify
  },
  data () {
    const validateCode = (rule, value, callback) => {
      if (this.identifyCode !== value) {
        this.refreshCode()
        callback(new Error('请输入正确的验证码'))
      } else {
        callback()
      }
    }
    return {
      imgs: [
        require('../../assets/images/login_bg/img100.jpg'),
        require('../../assets/images/login_bg/img101.jpg'),
        require('../../assets/images/login_bg/img102.jpg'),
        require('../../assets/images/login_bg/img103.jpg'),
        require('../../assets/images/login_bg/img104.jpg'),
        require('../../assets/images/login_bg/img105.jpg'),
        require('../../assets/images/login_bg/img106.jpg')
      ],
      index: 0,
      loading: false,
      rememberMe: false,

      loginForm: {
        username: '',
        password: '',
        code: ''
      },
      identifyCodes: '1234567890',
      identifyCode: '',
      loginRules: {
        username: [
          { required: true, trigger: 'blur', message: '请输入用户名' },
          { min: 3, max: 8, message: '长度在3-8字符之间', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在6-15字符之间', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入验证码', trigger: 'blur' },
          { validator: validateCode, trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    Year () {
      var date = new Date()
      return date.getFullYear()
    }
  },
  methods: {
    // 登录处理
    handleLogin () {
      this.$refs.loginForm.validate(async (valid) => {
        if (valid) {
          this.loading = true
          const { data: res } = await this.$http.post('/user/login', { phone: this.loginForm.username, password: this.loginForm.password })
          console.log(res)
          if (res.code !== 200) {
            this.loading = false
            return this.$message.error('登陆失败！')
          } else {
            if (this.rememberMe) {
              this.setCookie('username', this.loginForm.username, 7)
              this.setCookie('password', Base64.encode(this.loginForm.password), 7)
            } else {
              this.clearCookie('username')
              this.clearCookie('password')
            }
            window.sessionStorage.setItem('token', res.data.token)
            this.$message.success('登陆成功！')
            this.$router.push('/home') // 跳转到home页
            this.loading = false
          }
        }
      })
    },
    // 时间间隔改变背景图片
    changeImg () {
      var imgBg = document.getElementById('Login')
      setInterval(() => {
        if (this.index < this.imgs.length - 1) {
          this.index++
        } else {
          this.index = 0
        }
        // 修复切换背景图片出现的 “白色闪屏”现象
        const img = new Image()
        img.src = this.imgs[this.index]
        // 确定图片加载完成后在进行背景图片切换
        img.onload = function () {
          imgBg.style.backgroundImage = 'url(' + img.src + ')'
        }
      }, 7000)
    },

    // 设置cookie
    setCookie (c_name, value, expiredays) {
      var exdate = new Date()
      exdate.setDate(exdate.getDate() + expiredays)
      document.cookie = c_name + '=' + escape(value) + ';expires=' + exdate.toGMTString() + ';path=/'
    },
    // 读取cookie
    getCookie (c_name) {
      if (document.cookie.length > 0) {
        var c_start = document.cookie.indexOf(c_name + '=')
        if (c_start !== -1) {
          c_start = c_start + c_name.length + 1
          var c_end = document.cookie.indexOf(';', c_start)
          if (c_end === -1) c_end = document.cookie.length
          return unescape(document.cookie.substring(c_start, c_end))
        }
      }
    },
    // 检查cookie
    checkCookie (c_name) {
      var myCookie = this.getCookie(c_name)
      console.log(myCookie)
      if (myCookie !== null && myCookie !== '') return true
      else return false
    },
    // 清除cookie
    clearCookie (name) {
      this.setCookie(name, '', -1)
    },

    // 验证码生成
    randomNum (min, max) {
      return Math.floor(Math.random() * (max - min) + min)
    },
    refreshCode () {
      this.identifyCode = ''
      this.makeCode(this.identifyCodes, 4)
    },
    makeCode (o, l) {
      for (let i = 0; i < l; i++) {
        this.identifyCode += this.identifyCodes[
          this.randomNum(0, this.identifyCodes.length)
        ]
      }
    }
  },
  mounted () {
    this.changeImg()
  },
  created () {
    this.refreshCode()

    var username = this.getCookie('username')
    var password = this.getCookie('password')
    if (username && password) {
      this.loginForm.username = username
      this.loginForm.password = Base64.decode(password)
      this.rememberMe = true
    }
  }
}
</script>

<style lang="scss" scoped>
#Login {
    height: 100%;
    width:100%;
    overflow: hidden;
    z-index: -10;
    transition: all 2s;
    background-image: url('../../assets/images/login_bg/img100.jpg');
    background-repeat: no-repeat;
    background-size: cover; -webkit-background-size: cover; -o-background-size: cover;
    background-position: center 0;
}
.loginForm {
    width: 400px;
    border-radius: 6px;
    background: rgba(255, 255, 255, 0.9);
    padding: 25px 25px 5px 25px;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    .title {
        margin: 0 auto 30px auto;
        text-align: center;
        color: #707070;
        font-size: 1.4rem;
    }
    .login-code {
        float: right;
        cursor: pointer;
    }
}
.login_footer{
    position: fixed;
    bottom: 0;
    width: 100%;
    height: 40px;
    line-height: 40px;
    text-align: center;
    color: #fff;
    font-family: Arial;
    font-size: 12px;
    letter-spacing: 1px;
}
</style>
